package com.xmtlxx.web.controller.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Property;
import com.xmtlxx.oms.domain.Staging;
import com.xmtlxx.oms.domain.bo.PropertyBo;
import com.xmtlxx.oms.domain.vo.ClassifyVo;
import com.xmtlxx.oms.domain.vo.PropertyVo;
import com.xmtlxx.oms.domain.vo.TaskDtlVo;
import com.xmtlxx.oms.mapper.ClassifyMapper;
import com.xmtlxx.oms.mapper.PropertyMapper;
import com.xmtlxx.oms.mapper.StagingMapper;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.web.controller.center.service.impl.CommonServiceImpl;
import com.xmtlxx.web.controller.oms.service.IPropertyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 财物Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PropertyServiceImpl implements IPropertyService {

    private final PropertyMapper baseMapper;

    private final SysOssMapper sysOssMapper;

    private final SysDeptMapper sysDeptMapper;

    private final ClassifyMapper classifyMapper;

    private final StagingMapper stagingMapper;

    private final CommonServiceImpl commonService;

    /**
     * 查询财物
     *
     * @param id 财物主键
     * @return 财物
     */
    @Override
    public PropertyVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        PropertyVo vo = baseMapper.selectPropertyVoByID(id);
        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjid(vo.getPno());
        ossBo.setBuss("property");
        vo.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
        return vo;
    }

    @Override
    public Boolean queryByPno(String pno) {

        Boolean flag = true;
        PropertyVo propertyVo = baseMapper.selectVoOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, pno));
        if (propertyVo != null) {
            ClassifyVo classifyVo = classifyMapper.selectVoById(propertyVo.getThirdClassifyId());
            if (classifyVo != null) {
                if (classifyVo.getLevel() == 2 && classifyVo.getName().equals("交通工具")) {
                    flag = false;
                }
            }
        }
        return flag;
    }

    @Override
    public String queryPnoByRegion(String pno) {

        PropertyVo propertyVo = baseMapper.selectVoOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, pno));
        SysDept sysDept = sysDeptMapper.selectVoById(propertyVo.getOfficeId());
        return sysDept.getRegion();
    }

    /**
     * 查询财物列表
     *
     * @param bo 财物
     * @return 财物
     */
    @Override
    public TableDataInfo<PropertyVo> queryPageList(PropertyBo bo, PageQuery pageQuery) {

        SysDept dept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if (dept != null && StringUtils.isNotBlank(dept.getDeptCode())) {
            if (dept.getDeptCode().startsWith("3504")) {
                bo.setIsSecurity("1");
            }
        }
        // LambdaQueryWrapper<Property> lqw = buildQueryWrapper(bo);
        // Page<PropertyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<PropertyVo> result = baseMapper.selectPagePropertyList(pageQuery.build(), bo);
//        if(result != null && result.getRecords() != null && result.getRecords().size() > 0){
//            for (PropertyVo propertyVo:result.getRecords()){
//                SysOssBo ossBo = new SysOssBo();
//                ossBo.setObjid(propertyVo.getPno());
//                ossBo.setBuss("property");
//                propertyVo.setOss(sysOssMapper.selectSysOssList(ossBo));
//
//                //当前保管单位
//                SysDept sysDept = sysDeptMapper.selectVoById(propertyVo.getBelongDeptId());
//                if(sysDept != null && sysDept.getLevel() != null){
//                    if(sysDept.getLevel() == 1){
//                        propertyVo.setBelongDeptName("所队保管室");
//                    }
//                    if(sysDept.getLevel() == 2){
//                        propertyVo.setBelongDeptName("区县暂存库");
//                    }
//                    if(sysDept.getLevel() == 3){
//                        propertyVo.setBelongDeptName("中心库");
//                    }
//                }
//            }
//        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<PropertyVo> queryPageListNew(PropertyBo bo, PageQuery pageQuery) {

        SysDept dept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if (dept != null && StringUtils.isNotBlank(dept.getDeptCode())) {
            if (dept.getDeptCode().startsWith("3504")) {
                bo.setIsSecurity("1");
            }
        }
        Page<PropertyVo> result = baseMapper.selectPagePropertyListNew(pageQuery.build(), bo);

        return TableDataInfo.build(result);
    }

    /**
     * 查询财物列表
     *
     * @param bo 财物
     * @return 财物
     */
    @Override
    public List<PropertyVo> queryList(PropertyBo bo) {
        // LambdaQueryWrapper<Property> lqw = buildQueryWrapper(bo);
        // return baseMapper.selectVoList(lqw);
        return baseMapper.selectPropertyList(bo);
    }

    private LambdaQueryWrapper<Property> buildQueryWrapper(PropertyBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Property> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Property::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getPno()), Property::getPno, bo.getPno());
        lqw.eq(StringUtils.isNotBlank(bo.getClassifyId()), Property::getClassifyId, bo.getClassifyId());
        lqw.eq(StringUtils.isNotBlank(bo.getRfid()), Property::getRfid, bo.getRfid());
        lqw.eq(StringUtils.isNotBlank(bo.getLocatorId()), Property::getLocatorId, bo.getLocatorId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Property::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Property::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增财物
     *
     * @param bo 财物
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PropertyBo bo) {

        Property add = BeanUtil.toBean(bo, Property.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改财物
     *
     * @param bo 财物
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PropertyBo bo) {

        Property update = BeanUtil.toBean(bo, Property.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Property entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除财物
     *
     * @param ids 需要删除的财物主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deletePropertyWithStaging(String id) {

        Property property = baseMapper.selectById(id);
        boolean flag = false;
        Staging staging = stagingMapper.selectOne(new LambdaQueryWrapper<Staging>().eq(Staging::getPno, property.getPno()));
        flag = baseMapper.deleteById(property) > 0;

        if (flag) {
            commonService.StagingDelPush(staging);
        }

        return flag;
    }

    @Override
    public List<TaskDtlVo> initTaskDtls(String[] ids) {

        List<TaskDtlVo> vos = new ArrayList<>();
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                PropertyVo property = baseMapper.selectPropertyVoByID(id);
                TaskDtlVo vo = new TaskDtlVo();
                BeanUtil.copyProperties(property, vo, "id");

                SysOssBo ossBo = new SysOssBo();
                ossBo.setBuss("property");
                ossBo.setObjid(property.getPno());
                vo.setOss(sysOssMapper.selectSysOssList(ossBo));
                vos.add(vo);
            }
        }
        return vos;
    }

    @Override
    public PropertyVo queryByNo(String no) {

        PropertyVo vo = baseMapper.selectPropertyVoByPno(no);
        if (vo != null) {
            SysOssBo ossBo = new SysOssBo();
            ossBo.setObjid(vo.getPno());
            ossBo.setBuss("property");
            vo.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
            return vo;
        }
        return null;
    }

    @Override
    public Long getPropertyNums(PropertyBo bo) {

        long result = 0l;
        LambdaQueryWrapper<Property> lqw = Wrappers.lambdaQuery();
        String key = bo.getKey();
        List<String> keys = Arrays.asList(key.split("/"));
        if (keys.get(0).equals("CL")) {
            String carkey = keys.get(keys.size() - 1);
            result = Long.parseLong(carkey.replaceAll("\\D+", ""));
        } else {
            lqw.like(Property::getQrcode, key);
            result = baseMapper.selectCount(lqw);
            result = result + 1;
        }

        return result;
    }

    @Override
    public boolean updateProEvaluate(String pno) {

        LambdaUpdateWrapper<Property> updateWrapper = new LambdaUpdateWrapper<Property>()
                .eq(Property::getPno, pno).eq(Property::getDelFlag, 0)
                .set(Property::getEvaluate, 1);

        return baseMapper.update(new Property(), updateWrapper) > 0;
    }

}
